package com.bclz.interception;

import java.io.PrintWriter;
import java.io.Serializable;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.bclz.common.response.ResponseUtils;

import net.sf.json.JSONObject;


/**
 * 
* Title: AuthControInterception  
* Description:拦截需要登陆页面   
* @author xuchang  
* @date 2018年8月7日
 */
@Component
public class AuthControInterception implements HandlerInterceptor {
	
	
	@Autowired
	private RedisTemplate<String, Serializable> redisTemplate;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		// TODO Auto-generated method stub
		
		String skey=request.getParameter("skey");
		if(skey==null||redisTemplate.opsForValue().get(skey)==null) {
			response.setHeader("Content-type", "text/html;charset=UTF-8");
			response.setCharacterEncoding("UTF-8");
			PrintWriter printWriter = response.getWriter();
			printWriter.write(JSONObject.fromObject(ResponseUtils.fail("请先登录!", null)).toString());
			printWriter.close();
			return false;
		}else {
			redisTemplate.expire(skey, 30, TimeUnit.MINUTES);
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
		
	}
	
	
	
	
	
	
}
